<template>
  <div class="schedule-selector">
    <!-- Day selector -->
    <a-space size="large">
      <div>星期</div>
      <a-select
        v-model:value="selectedDay"
        allowClear="true"
        style="width: 100px"
      >
        <a-select-option
          v-for="(day, index) in days"
          :key="index + 1"
          :value="index + 1"
        >
          {{ day }}
        </a-select-option>
      </a-select>

      <div>节次</div>
      <a-select
        v-model:value="selectedSession"
        allowClear="true"
        style="width: 100px"
      >
        <a-select-option
          v-for="item in uniqueSessions"
          :key="item"
          :value="item"
        >
          {{ sessionText(item) }}
        </a-select-option>
      </a-select>
    </a-space>

    <!-- <a-button
      type="primary"
      @click="handleConfirmScheduling"
      style="width: 100px"
    >
      确认排课
    </a-button> -->
    <a-table
      :columns="columns"
      :loading="loading"
      :data-source="selectedLabIds"
      
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button type="primary" @click="openConfirmModal(record)">
            确认排课
          </a-button>
        </template>
      </template>
    </a-table>

    <a-modal
      title="确认排课"
      v-model:visible="confirmModalVisible"
      centered="true"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleConfirmScheduling"
      @cancel="closeConfirmModal"
    >
      <p>确认为该教师添加排课吗？</p>
    </a-modal>

    <a-modal
      title="排课成功"
      v-model:visible="successModalVisible"
      centered="true"
      ok-text="确认"
      @ok="handleSuccessModalOk"
    >
      <p>已成功为该教师添加排课。</p>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref, computed } from "vue";
import {
  checkTeacherApply,
  teacherApply,
  managementForTeacher,
} from "@/api/methods/adminReq";
import { labInfo } from "@/utils/userInfo";

const route = useRoute();
const router = useRouter();
const loading = ref(false);

const queryParams = {
  labType: route.query.labType,
  semesterId: route.query.semesterId,
  beginWeek: route.query.beginWeek,
  endWeek: route.query.endWeek,
  studentNum: route.query.studentNum,
  amountOfSession: route.query.amountOfSession,
};

const columns = [
  {
    title: "实验室",
    dataIndex: "",
    key: "",
    width: "50%",
    customRender: ({ text, record }) => {
      return translateLabId(text);
    },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: "50%",
  },
];

/* const rowSelection = {
  selectedRowKeys: ref([]),
  onChange: (selectedRowKeys: number, selectedRows: any[]) => {
    rowSelection.selectedRowKeys.value = selectedRowKeys;
  },
}; */

onMounted(async () => {
  loading.value = true;
  const { data: res } = await checkTeacherApply(queryParams);
  reflectMapDataSource(res);
  loading.value = false;
});

const session = ref([]);
const labIds = ref([]);

const reflectMapDataSource = (res: any) => {
  session.value = res.session;
  labIds.value = res.labIds;
};

const days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

const dataSource = computed(() => {
  const merged = [];
  for (let i = 0; i < session.value.length; i++) {
    const [day, sessionNum] = session.value[i];
    const labIdsForSession = labIds.value[day][sessionNum] || [];
    for (const labId of labIdsForSession) {
      merged.push({ day, session: sessionNum, labId });
    }
  }
  return merged;
});

const filteredDataSource = computed(() => {
  return dataSource.value.filter((item) => item.day === selectedDay.value);
});

const uniqueSessions = computed(() => {
  return Array.from(
    new Set(filteredDataSource.value.map((item) => item.session))
  );
});

const selectedDay = ref(1);
const selectedSession = ref(1);
const selectedLab = ref();

const selectedLabIds = computed(() => {
  return filteredDataSource.value
    .filter((item) => item.session === selectedSession.value)
    .map((item) => item.labId);
});

const sessionText = (session: any) => {
  switch (session) {
    case 1:
      return "1-2";
    case 2:
      return "3-5";
    case 3:
      return "6-7";
    case 4:
      return "8-9";
    case 5:
      return "10-12";
    case 6:
      return "13-15";
    default:
      return "--";
  }
};

const confirmModalVisible = ref(false);

const openConfirmModal = (labId: number) => {
  selectedLab.value = labId;
  confirmModalVisible.value = true;
};

const closeConfirmModal = () => {
  confirmModalVisible.value = false;
};

const successModalVisible = ref(false);

const handleConfirmScheduling = async () => {
  const labIdsQuery = [];
  for (let i = 0; i <= selectedDay.value; i++) {
    labIdsQuery.push([]);
  }
  for (let i = 0; i < selectedSession.value; i++) {
    labIdsQuery[selectedDay.value].push([]);
  }
  labIdsQuery[selectedDay.value].push([selectedLab.value]);
  const queryParams = {
    state: 1,
    teacherId: route.query.teacherId,
    teacherName: route.query.teacherName,
    semesterId: route.query.semesterId,
    semesterName: route.query.semesterName,
    courseName: route.query.courseName,
    beginWeek: route.query.beginWeek,
    endWeek: route.query.endWeek,
    id: route.query.id,
    labType:route.query.labType,
    className:route.query.className,
    session: [[selectedDay.value, selectedSession.value]],
    labIds: labIdsQuery,
  };
  closeConfirmModal();
  await managementForTeacher(queryParams);
  successModalVisible.value = true;
};

const handleSuccessModalOk = () => {
  successModalVisible.value = false;
  router.back();
};

const translateLabId = (text) => {
  const labName = labInfo.value.find((i) => i.id === text).name;
      return labName || "名字不存在";
};
</script>

<style>
.schedule-selector {
  display: flex;
  flex-direction: column;
}

.lab-id-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.base-color {
  background-color: #1890ff;
  color: white;
}

a-button:not(.base-color) {
  background-color: #ccc;
  color: black;
}
</style>
